﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SIA.Configurators;
using SIA.HwAccess;
using SIA.DataBase;
using SIA.Allarms;

namespace SIA.Managers.Allarms
{
    public class AllarmsManager
    {
        private IAllarmsCollections _allarmsList = new GenericAllarmsCollecions();
        private IAllarmsCollections _activeAllarms = new ActiveAllarmsCollecions();
        private IDBArchive _dBArchive = null;

        public IAllarmsCollections AllarmsList { get { return _allarmsList; } }
        public IAllarmsCollections ActiveAllarms { get { return _activeAllarms; } }

        public AllarmsManager(IDictionaryProperty allarmsProperty, IHwSignals signals, IDBArchive dBArchive)
        {
            foreach (IDictionaryProperty allarmProp in allarmsProperty.Values)
            {
                switch (allarmProp["ALLARMTYPE"].PropertyValue.ToUpper())
                {
                    case "DIGITALALLARM":
                        _allarmsList.Add(new DigitalAllarm(allarmProp, (IDigitalSignal)signals[allarmProp["NOMESEGNALE"].PropertyValue]));
                        break;
                    default:
                        throw new Exception("Tipo di Allarme ancora non Supportato");
                }
            }
            _dBArchive = dBArchive;
            _allarmsList.RiseONAllarm += new AllarmEvent(_allarmsList_RiseONAllarm);
            //_activeAllarms.RiseIsArchiviableAllarm += new AllarmEvent(_activeAllarms_RiseIsArchiviableAllarm);
        }

        //void _activeAllarms_RiseIsArchiviableAllarm(IAllarm allarm)
        //{
        //    _dBArchive.savePastAllarm(allarm);
        //    _activeAllarms.Remove(allarm);
        //}

        void _allarmsList_RiseONAllarm(IAllarm allarm)
        {
            IAllarm ac = allarm.clone();
            _activeAllarms.Add(ac);         //inserisco una copia dell'allarme
            allarm.clean();                 //pulisco l'allarme e lo rendo disponibile per un nuovo allarme
            ac.RiseIsArchiviableAllarm += new AllarmEvent(ac_RiseIsArchiviableAllarm);
        }

        void ac_RiseIsArchiviableAllarm(IAllarm allarm)
        {
            try
            {
                _dBArchive.savePastAllarm(allarm);
                _activeAllarms.Remove(allarm);
            }
            catch (Exception ex)
            {
                SIA.Messages.MessageManager.sendMessage(this, "ac_RiseIsArchiviableAllarm", ex);
            }
            
        }

    }
}
